package com.wb.mas.ui.auth;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.DictInfoTypeKey;
import com.wb.mas.app.SPKeys;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.ContactInfoBean;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.DicInfoResponse;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.utils.response.ResultException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthContactViewModel extends AuthBaseViewModel {
    private String currentDictType;
    private List<DicInfoEntity> dicInfoList;

    private int contactPos = 0;//表示 联系人的  索引

    public AuthContactViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
        setTitleText(getString(R.string.auth_contact_page_tile));

    }

    public void setUiNameAndNum(String name, String phoneNumber) {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phoneNumber)) {
            ToastUtils.showShort("name or phone is null");
            return;
        }


        if (phoneNumber.equalsIgnoreCase(contactPhone1.get())
                || phoneNumber.equalsIgnoreCase(contactPhone2.get())
                || phoneNumber.equalsIgnoreCase(contactPhone3.get())
                || phoneNumber.equalsIgnoreCase(contactPhone4.get())
                || phoneNumber.equalsIgnoreCase(contactPhone5.get())
        ) {

            ToastUtils.showShort(getString(R.string.phone_repeat));
            return;
        }

        if (contactPos == 1) {
            contactName1.set(name);
            contactPhone1.set(phoneNumber);
        } else if (contactPos == 2) {
            contactName2.set(name);
            contactPhone2.set(phoneNumber);
        } else if (contactPos == 3) {
            contactName3.set(name);
            contactPhone3.set(phoneNumber);
        } else if (contactPos == 4) {
            contactName4.set(name);
            contactPhone4.set(phoneNumber);
        } else if (contactPos == 5) {
            contactName5.set(name);
            contactPhone5.set(phoneNumber);
        }
    }


    public class UiChangeEvent {
        public SingleLiveEvent<String> showPopupEvent = new SingleLiveEvent();
        public SingleLiveEvent<String> selectContact = new SingleLiveEvent();
    }

    public UiChangeEvent uc = new UiChangeEvent();

    public ObservableField<String> contactName1 = new ObservableField<>();
    public ObservableField<String> contactPhone1 = new ObservableField<>();
    public ObservableField<DicInfoEntity> contactRealtion1 = new ObservableField<>();

    public ObservableField<String> contactName2 = new ObservableField<>();
    public ObservableField<String> contactPhone2 = new ObservableField<>();
    public ObservableField<DicInfoEntity> contactRealtion2 = new ObservableField<>();

    public ObservableField<String> contactName3 = new ObservableField<>();
    public ObservableField<String> contactPhone3 = new ObservableField<>();
    public ObservableField<DicInfoEntity> contactRealtion3 = new ObservableField<>();

    public ObservableField<String> contactName4 = new ObservableField<>();
    public ObservableField<String> contactPhone4 = new ObservableField<>();
    public ObservableField<DicInfoEntity> contactRealtion4 = new ObservableField<>();

    public ObservableField<String> contactName5 = new ObservableField<>();
    public ObservableField<String> contactPhone5 = new ObservableField<>();
    public ObservableField<DicInfoEntity> contactRealtion5 = new ObservableField<>();

    private ObservableField<DicInfoEntity> tempSelectedRelation;


    public BindingCommand contact1Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            contactPos = 1;

            uc.selectContact.setValue("");
        }
    });
    public BindingCommand contact2Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            contactPos = 2;
            uc.selectContact.setValue("");

        }
    });
    public BindingCommand contact3Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            contactPos = 3;
            uc.selectContact.setValue("");

        }
    });
    public BindingCommand contact4Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            contactPos = 4;
            uc.selectContact.setValue("");

        }
    });
    public BindingCommand contact5Click = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            contactPos = 5;
            uc.selectContact.setValue("");

        }
    });


    public BindingCommand contactRelationClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            tempSelectedRelation = contactRealtion1;
            getDictsBykey(DictInfoTypeKey.common_relation);
        }
    });
    public BindingCommand contactRelationClick2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelectedRelation = contactRealtion2;
            getDictsBykey(DictInfoTypeKey.common_relation);

        }
    });

    public BindingCommand contactRelationClick3 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelectedRelation = contactRealtion3;
            getDictsBykey(DictInfoTypeKey.common_relation);
        }
    });
    public BindingCommand contactRelationClick4 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            tempSelectedRelation = contactRealtion4;
            getDictsBykey(DictInfoTypeKey.common_relation);
        }
    });
    public BindingCommand contactRelationClick5 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            tempSelectedRelation = contactRealtion5;
            getDictsBykey(DictInfoTypeKey.common_relation);
        }
    });
    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (TextUtils.isEmpty(contactName1.get())
                    || TextUtils.isEmpty(contactPhone1.get())
                    || contactRealtion1.get() == null
                    || TextUtils.isEmpty(contactRealtion1.get().dictValue)

            ) {

                ToastUtils.showShort(R.string.auth_contact_please_input_contact1);
                return;
            }

            if (TextUtils.isEmpty(contactName2.get())
                    || TextUtils.isEmpty(contactPhone2.get())
                    || contactRealtion2.get() == null
                    || TextUtils.isEmpty(contactRealtion2.get().dictValue)
            ) {

                ToastUtils.showShort(R.string.auth_contact_please_input_contact2);
                return;
            }
            if (TextUtils.isEmpty(contactName3.get())
                    || TextUtils.isEmpty(contactPhone3.get())
                    || contactRealtion3.get() == null
                    || TextUtils.isEmpty(contactRealtion3.get().dictValue)
            ) {

                ToastUtils.showShort(R.string.auth_contact_please_input_contact3);
                return;
            }
            if (TextUtils.isEmpty(contactName4.get())
                    || TextUtils.isEmpty(contactPhone4.get())
                    || contactRealtion4.get() == null
                    || TextUtils.isEmpty(contactRealtion4.get().dictValue)
            ) {

                ToastUtils.showShort(R.string.auth_contact_please_input_contact4);
                return;
            }
            if (TextUtils.isEmpty(contactName5.get())
                    || TextUtils.isEmpty(contactPhone5.get())
                    || contactRealtion5.get() == null
                    || TextUtils.isEmpty(contactRealtion5.get().dictValue)

            ) {

                ToastUtils.showShort(R.string.auth_contact_please_input_contact5);
                return;
            }

            uploadContactInfo();
        }
    });

    private void uploadContactInfo() {

        showDialog();
        Map<String, Object> params = new HashMap<>();

        params.put("authPageCode", Constants.AUTH_PAGE_CODE_CONTACTS_CODE);
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            params.put("isInformationWrong", "1");

        }
        List<ContactInfoBean> contacts = new ArrayList<>();
        contacts.add(new ContactInfoBean(contactPhone1.get(), "1", contactRealtion1.get().dictCode, contactName1.get()));
        contacts.add(new ContactInfoBean(contactPhone2.get(), "2", contactRealtion2.get().dictCode, contactName2.get()));
        contacts.add(new ContactInfoBean(contactPhone3.get(), "3", contactRealtion3.get().dictCode, contactName3.get()));
        contacts.add(new ContactInfoBean(contactPhone4.get(), "4", contactRealtion4.get().dictCode, contactName4.get()));
        contacts.add(new ContactInfoBean(contactPhone5.get(), "5", contactRealtion5.get().dictCode, contactName5.get()));
        params.put("paramList", contacts);

        model.saveOrUpdateContactsInfo(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {


                        dismissDialog();
                        if (rootApiBean != null && rootApiBean.getStatus() == 200) {
                            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_CONTACTS_CODE);
                            finish();

                        } else {
                            if (!TextUtils.isEmpty(rootApiBean.getMessage())) {
                                ToastUtils.showShort(rootApiBean.getMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();

                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                        KLog.e("error:" + throwable.getMessage());
                    }
                });

    }

    private List<DicInfoEntity> dicListData;

    public void getDictsBykey(final String dictType) {
        if (dicListData != null && dicListData.size() > 0) {
            showPopWindow(dictType, dicListData);
            return;
        }

        showDialog();
        Map<String, Object> dictParams = new HashMap<>();
        dictParams.put("dictType", dictType);
        model.getDicInfo(dictParams)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DicInfoResponse>() {

                    @Override
                    public void accept(DicInfoResponse dicInfoResponse) throws Exception {
                        dismissDialog();
                        if (dicInfoResponse == null) return;

                        dicListData = dicInfoResponse.getData();

                        showPopWindow(dictType, dicListData);


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }


    private void showPopWindow(String dictType, List<DicInfoEntity> data) {
        this.currentDictType = dictType;
        this.dicInfoList = data;
        uc.showPopupEvent.setValue("");
    }


    public String getCurrentDictType() {
        return this.currentDictType;
    }

    public List<DicInfoEntity> getCurrentDictList() {
        return this.dicInfoList;
    }


    public void onItemSelected(String title, int position) {
        if (currentDictType == null || dicInfoList == null || position >= dicInfoList.size() || tempSelectedRelation == null)
            return;
        tempSelectedRelation.set(dicInfoList.get(position));
    }


    @Override
    public void onCreate() {
        super.onCreate();
        getSubmitedInfo(Constants.AUTH_PAGE_CODE_CONTACTS_CODE);
    }


    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);
        if (response != null && response.getData() != null && response.getData().getContactsInfo() != null) {
            SubmitedAuthResponse.DataBean.ContactsInfoBean contactsInfo = response.getData().getContactsInfo();
            List<SubmitedAuthResponse.DataBean.ContactsInfoBean.ContactsInfosBean> contactsInfos = contactsInfo.getContactsInfos();

            if (contactsInfos != null) {
                for (int i = 0; i < contactsInfos.size(); i++) {
                    SubmitedAuthResponse.DataBean.ContactsInfoBean.ContactsInfosBean contactsInfosBean = contactsInfos.get(i);
                    if (i == 0) {

                        contactName1.set(contactsInfosBean.getUserName());
                        contactPhone1.set(contactsInfosBean.getMobile());
                        contactRealtion1.set(new DicInfoEntity(contactsInfosBean.getRelationValue(), contactsInfosBean.getRelation()));
                    } else if (i == 1) {
                        contactName2.set(contactsInfosBean.getUserName());
                        contactPhone2.set(contactsInfosBean.getMobile());
                        contactRealtion2.set(new DicInfoEntity(contactsInfosBean.getRelationValue(), contactsInfosBean.getRelation()));

                    } else if (i == 2) {
                        contactName3.set(contactsInfosBean.getUserName());
                        contactPhone3.set(contactsInfosBean.getMobile());
                        contactRealtion3.set(new DicInfoEntity(contactsInfosBean.getRelationValue(), contactsInfosBean.getRelation()));

                    } else if (i == 3) {
                        contactName4.set(contactsInfosBean.getUserName());
                        contactPhone4.set(contactsInfosBean.getMobile());
                        contactRealtion4.set(new DicInfoEntity(contactsInfosBean.getRelationValue(), contactsInfosBean.getRelation()));

                    } else if (i == 4) {
                        contactName5.set(contactsInfosBean.getUserName());
                        contactPhone5.set(contactsInfosBean.getMobile());
                        contactRealtion5.set(new DicInfoEntity(contactsInfosBean.getRelationValue(), contactsInfosBean.getRelation()));

                    }
                }
            }

        }
    }


}
